from sqlalchemy import create_engine, Column, String, TIMESTAMP, text, DECIMAL, Date, Integer
from sqlalchemy.orm import sessionmaker, scoped_session, Session
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class SqlPath:
    driver, table_name_prefix, pool_size, max_overflow, pool_recycle = 'mysql+pymysql', '', 100, 100, 60
    host, port, username, password, database, charset, echo = 'localhost', '3306', 'root', '', '', 'utf8mb4', True

    def get_url(self):
        # 配置数据库地址：数据库类型+数据库驱动名称://用户名:密码@机器地址:端口号/数据库名
        return f"""{self.driver}://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}?charset={self.charset}"""


def engine_db(config):
    """
    :param config: 链接数据库配置
    :return: 链接数据库
    """
    return create_engine(config.get_url(), pool_size=config.pool_size, max_overflow=config.max_overflow,
                         pool_recycle=config.pool_recycle, echo=config.echo)


class SqlDB:
    def __init__(self, some_model):
        self.SessionMaker = sessionmaker(autocommit=False, autoflush=False, bind=engine_db(sql_path))
        self.session = self.SessionMaker()
        self.SomeModel = some_model

    def __del__(self):
        """ 关闭链接 """
        self.session.close()

    def session_commit(self):
        """ sql事务 """
        self.session.commit()


sql_path = SqlPath()
sql_path.host = '127.0.0.1'
sql_path.port = '3306'
sql_path.username = 'root'
sql_path.password = '123456789'
sql_path.database = 'myblog'
sql_path.echo = False
